package quotation.utils;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.StrUtil;
import lombok.extern.slf4j.Slf4j;
import net.coobird.thumbnailator.Thumbnails;
import org.apache.commons.lang3.StringUtils;
import quotation.exception.BusinessException;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

/**
 * @Function:
 * @Author ICBC - BOSS_Hang
 * @Date 2021/3/2
 */
@Slf4j
public class FileUploadUtils {


    private static String getFileMap(String suffix) {

        Map<String, String> map = new HashMap();
        map.put(".bmp", "picture");
        map.put(".BMP", "picture");
        map.put(".png", "picture");
        map.put(".PNG", "picture");
        map.put(".gif", "picture");
        map.put(".GIF", "picture");
        map.put(".jpeg", "picture");
        map.put(".JPEG", "picture");
        map.put(".jpg", "picture");
        map.put(".JPG", "picture");
        //转小写
        suffix = suffix.toLowerCase();
        return map.get(suffix);
    }


    public static boolean canLoad(String mode) {

        if (StringUtils.isEmpty(mode)) {
            return false;
        }

        String fileMap = getFileMap(mode);


//        if (!fileMap.containsKey(mode)) {
//            return false;
//        }
//        return true;

        return StrUtil.isNotEmpty(fileMap);
    }

    public static Boolean resize1(InputStream inputStream, String fileName, String uploadDir) throws Exception {
        if (inputStream == null) {
            return false;
        }
        // 不支持 缩放
        BufferedImage src = ImageIO.read(inputStream);

        int old_w = src.getWidth();
        // 得到源图宽
        int old_h = src.getHeight();
        // 得到源图长
        BufferedImage newImg = null;
        // 判断输入图片的类型
        switch (src.getType()) {
            case 13:
                // png,gif
                newImg = new BufferedImage(old_w, old_h, BufferedImage.TYPE_4BYTE_ABGR);
                break;
            default:
                newImg = new BufferedImage(old_w, old_h, BufferedImage.TYPE_INT_RGB);
                break;
        }
        Graphics2D g = newImg.createGraphics();
        // 从原图上取颜色绘制新图
        g.drawImage(src, 0, 0, old_w, old_h, null);
        g.dispose();
        // 根据图片尺寸压缩比得到新图的尺寸
        newImg.getGraphics().drawImage(src.getScaledInstance(old_w, old_h, Image.SCALE_SMOOTH), 0, 0, null);
        File newFile = new File(uploadDir + fileName);
        String endName = fileName.substring(fileName.lastIndexOf(".") + 1).toLowerCase();
        boolean write = ImageIO.write(newImg, endName, newFile);
        //删除复制的文件
        newFile.delete();
        if (inputStream != null){
            inputStream.close();
        }
        return write;
    }

    /**
     * 递归 压缩图片流，到指定大小范围内
     *
     * @param inputStream       文件流
     * @param limitSize         开始压缩的大小 字节Byte(B)
     * @param fileName          文件名称   aa.png
     * @param k                 递归次数
     * @return
     * @throws IOException
     */
    public static InputStream changeSize(InputStream inputStream, Long limitSize,String fileName,int k) throws IOException {

        //先判断 文件大小是否超过 规定大小。字节Byte(B)
        if ((inputStream.available() < limitSize)|| k <=0) {
            return inputStream;
        }
        // 获取文件后缀
        String suffix = FileUtil.getSuffix(fileName);
        if(StrUtil.isEmpty(suffix)){
            throw new BusinessException(fileName + ",文件后缀为空");
        }
        String fileMap = getFileMap(suffix);
        // 类型为空，直接返回
        if(StrUtil.isEmpty(fileMap)){
            return inputStream;
        }
        // 不是图片类型，直接返回
        if(!"picture".equals(fileMap)){
            return inputStream;
        }

        // 压缩比率为 0.75
        float ratio = 0.75f;
        BufferedImage bufImage = ImageIO.read(inputStream);
        // 判断是否是图片，不是图片直接返回不压缩
        if (bufImage == null || bufImage.getWidth(null) <= 0 || bufImage.getHeight(null) <= 0) {
            return inputStream;
        }
        //ByteArrayOutputStream bos = new ByteArrayOutputStream();

        //写入 临时文件
        String uuid = UUID.randomUUID().toString().replaceAll("-", "");
        String name = System.currentTimeMillis() + "_" + uuid +"." + suffix;
        File file = new File(name);
        inputStream.close();
        Thumbnails.of(bufImage)
                .scale(ratio)
                .toFile(file);
        //获取输出流
        inputStream = new FileInputStream(file);
        //删除临时文件
        boolean delete = file.delete();
        log.info("删除文件是否成功:" + delete);
        //递归调用
        k--;
        return changeSize(inputStream, limitSize, fileName,k);
    }

}
